
#include "epoll.h"
int main(int argc, char *argv[])
{
    int fd_listen = tcp_server_init("0", 8888, 20);
    ERROR_CHECK(fd_listen, -1, "tcp_server_init");
    // 创建epoll实例；
    int epfd = epoll_create(1);
    ERROR_CHECK(-1, epfd, "epoll_create");
    // 定义一个epoll_event变量，设置或修改，存储就绪IO；
    struct epoll_event event, read_events[50];
    // 将fd_listen 添加到epoll实例；
    event.data.fd = fd_listen;
    event.events = EPOLLIN;
    int ret = epoll_ctl(epfd, EPOLL_CTL_ADD, fd_listen, &event);
    ERROR_CHECK(-1, ret, "epoll_ctl->ADD");
    int fd;
    while (1)
    {
        ret = epoll_wait(epfd, read_events, 50, -1);
        ERROR_CHECK(-1, ret, "epoll_wait");
        for (int i = 0; i < ret; i++)
        {
            fd = read_events[i].data.fd;
            if (fd == fd_listen)
            {
                int fd_cnd = tcp_server_wait(fd);
                if (-1 == fd_cnd)
                {
                    perror("wait");
                    continue; /* code */
                }
                event.data.fd = fd_cnd;
                event.events = EPOLLIN;
                if (-1 == epoll_ctl(epfd, EPOLL_CTL_ADD, fd_cnd, &event))
                {
                    perror("epoll_ctl->add");
                    close(fd_cnd);
                    continue;
                }
            }
            else
            {
                if (-1 == sendfile(fd))
                {
                    struct sockaddr_in caddr;
                    socklen_t len = sizeof caddr;
                    getpeername(fd, (void *)&caddr, &len);
                    if (-1 == epoll_ctl(epfd, EPOLL_CTL_DEL, fd, NULL))
                    {
                        perror("epollctl->del");
                        return -1;
                    }

                    close(fd);
                    printf("client:%s:%d disconnected!\n", inet_ntoa(caddr.sin_addr),ntohs(caddr.sin_port));
                }
            }
        }
    }
    return 0;
}
